import axios from 'axios'
import qs from 'qs'
import { useCookies } from "vue3-cookies";
const { cookies } = useCookies();
let map = new Map()
// 创建axios实例
let timeout = 1000*10;
let instance = axios.create({timeout:timeout});
//设置POST请求头
instance.defaults.headers.post['Content-Type'] = 'application/json';
instance.defaults.baseURL = '/ajax';
//请求拦截器
instance.interceptors.request.use( config => {
    if(config.method == 'post'){
        config.data = JSON.stringify(config.data);
    }
    if( !map.has( config.url ) ){
        map.set( config.url )
        if( cookies.isKey('__token') ){
            config.headers[ 'Authorization' ] = cookies.get('__token') ;
        }
        return config;
    } else {
        return Promise.reject( { config , status : 0 , msg : 'request:repeat' } ) //重复请求
    }
},
error => { return Promise.reject( error ) })

//响应拦截器
instance.interceptors.response.use ( response => {
    console.log('response',response);
    
	if (response&&response.config) {
		map.delete( response.config[ 'url' ] )
	}
    if( response.data &&response.data.code&& response.data.code != 200 ) {
        errorHandle( response.data.code,  response.data.message )
        //return Promise.reject( response.data.error )
    } else return response.data;
},
error => {
    if (error&&error.config) {
		map.delete( error.config[ 'url' ] )
	}
    let {response} = error;
    if( response ){
        errorHandle( response.status )
        return Promise.reject( response )
    } else {
        //断网TODO::need 
    }
})

//处理错误
const errorHandle = ( responeStatus,msg ) => {
    switch( responeStatus ){
        case 401:
            //TODO::need 未登录，跳转到登录页，需要携带from
            break;
        case 403:
            // TODO::need 登录失效，跳转到登录页,需要携带from，清除token,
            break;
        default:
            uni.showToast({
				title: msg,
				icon: "none",
				duration: 3000
			})
    }
}

export default instance